package cz.muni.fi.pa165.sme.web.system;

import cz.muni.fi.pa165.sme.api.UserService;
import cz.muni.fi.pa165.sme.api.to.UserTO;
import cz.muni.fi.pa165.sme.web.fo.UserFO;
import org.apache.wicket.spring.injection.annot.SpringBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.core.convert.ConversionService;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Service;

/** @author jirankova */
@Service
public class SportManagerAuthenticationProvider implements AuthenticationProvider {

	@SpringBean(name = "userDetailsServiceImpl")
	private UserDetailsService userDetailsService;

	@SpringBean
	private UserService userService;

	@SpringBean(name = "conversionServiceFe")
	private ConversionService conversionService;

	@Override
	public Authentication authenticate(final Authentication authentication) throws AuthenticationException {

		final UsernamePasswordAuthenticationToken auth = (UsernamePasswordAuthenticationToken) authentication;
		final String username = (String) auth.getPrincipal();
		final String password = (String) auth.getCredentials();

		final UserDetails userDetails = userDetailsService.loadUserByUsername(username);

		if(password == null || !password.equals(userDetails.getPassword())) {
			throw new BadCredentialsException("Bad credentials for user "+username);
		}

		final UserTO userTO = userService.findUserByLogin(username);
		final UserFO userFO = conversionService.convert(userTO, UserFO.class);

		return new UsernamePasswordAuthenticationToken(userFO, null, userDetails.getAuthorities());
	}

	@Override
	public boolean supports(final Class<?> authentication) {
		return authentication.equals(UsernamePasswordAuthenticationToken.class);
	}
}
